<!--
 * @Author: 又帅又爱学习 501879094@qq.com
 * @Date: 2022-03-28 17:41:14
 * @LastEditors: 又帅又爱学习 501879094@qq.com
 * @LastEditTime: 2022-10-17 17:42:23
 * @FilePath: /vue_demo/src/views/Files.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div>
    文件流上传/下载
    <input
      v-if="fileState"
      ref="input"
      type="file"
      style="display: none;"
      @change="checkFile"
    >
    <div class="link">
      <a
        href="./学习成长.xls"
        style="color:#6AB0F6"
        type="primary"
        target="_blank"
      >下载模版</a>
    </div>
    <a href="javascript:;" class="btn" @click="fileClick">点击选择</a>
    <a href="javascript:;" class="btn" @click="downLoad">点击下载</a>
  </div>
</template>
<script>
export default {
  data() {
    return {
      fileState: true
    }
  },
  mounted() {
    // this.fileClick()
  },
  methods: {
    /**
     * @description: 描述
     * @return {*}
     * @author: lcw
     */
    fileClick() {
      console.log('fileClick1---', this.$refs.input.files)
      const DOM = this.$refs.input
      DOM.click()
    },
    checkFile() {
      console.log('checkFile')
      const DOM = this.$refs.input; const file = DOM.files[0]
      this.sendFile(file) // 发送文件
      // 重新生成input节点
      this.fileState = false
      window.setTimeout(() => {
        this.fileState = true
      })
    },
    sendFile(file, id) { // 通过 XMLHttpRequest 发送  注意FormData
      const xhr = new XMLHttpRequest()
      const data = new FormData()

      data.append('excel', file)
      data.append('fileID', id)

      xhr.onload = function() {
        if (xhr.status === 200 && xhr.status < 300 || xhr.status === 304) {
          try {
            // const data = JSON.parse(xhr.responseText)
            // callback(data)
          } catch (error) {
            console.log(`errMsg:${error}`)
          }
        }
      }
      xhr.open('post', 'www.sendFile.com', true)
      xhr.send(data)
    },
    downLoad() {
      const fileDate = this.getFile(`fileID=1`)
      const blob = new Blob([fileDate], { 'type': 'application/msexcel' }) // [文件]{类型}
      const a = this.$els.download

      a.download = 'excel.xls' // 下载的文件名
      a.href = window.URL.createObjectURL(blob)
    },
    async getFile(params) { // 通过 fetch 接收  注意.blob()
      const response = await fetch('www.getFile.com', {
        method: 'POST',
        credentials: 'include',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: params
      }).catch((error) => {
        console.error(error)
      })
      return await response.blob().catch((error) => {
        console.error(error)
      })
    }
  }
}
</script>
